#ifndef _TOWN_MANANGER_H_
#define _TOWN_MANANGER_H_

#include "Common.h"
#include "Resource.h"
#include "ResourceManager.h"
#include "Singleton.h"
#include "String.h"
#include "Threading/ThreadStarter.h"
#include "Threading/QueueThreadPool.h"

class TownPtr;

class  TownManager: public ResourceManager,public ThreadRunableBase,public Singleton<TownManager>
{
public:
	TownManager();
	~TownManager();

	String	getTownStringName(const uint32 & serial);
	
	ResourcePtr  create(const uint32 & serial,const NameValuePairList* params = 0);
	ResourceCreateOrRetrieveResult  \
		createOrRetrieve(const uint32 & serial,const NameValuePairList* params = 0);
	ResourcePtr  load(const uint32 & serial);
	ResourcePtr     reload(ResourceHandle handle);

	//user manager start
	void	Startup(const uint32 & gid,const uint32 & thread_min,const uint32 & thread_max = 0,bool isBattle = true);
	void 	Shutdown(void);

	//virual from  ThreadRunableBase
        bool  run(void *p);

	//开始城市处理线程
	bool    StartTownProcess(void);


	//根据查询，返回符合条件的记录 offset 为翻页起点 limitcount 为取回角色最大数量 query 为查询条件在 WHERE之后
	bool	getTownsList(std::list<TownPtr> * chars,const uint32 & offset,const uint32 & limitcount,const char * query,...);

	//根据查询条件返回一个查询结果数量 query 为在WHERE之后的SQL语句
	uint32	getDBCount(const char * query,...);

	//用于得到一个Mail结构，用于向数据库追加新效果的记录
	Resource * newDumyTown(void);
	void	freeDumyTown(Resource * dumy);

	//根据模板向数据库插入新的记录，返回插入的记录
	ResourcePtr	createTownDatabase(Resource * dumy);
	ResourcePtr	loadTownDatabase(Resource * dumy);



	ResourcePtr   newDBObject(void);
	ResourcePtr   getDBObjectByHandle(const uint32 & handle);
	bool	getDBObjects(std::list<ResourcePtr> * objs,const uint32 & offset,const uint32 & limitcount,const char * query,...);



	const uint32 & getCurrentUpdateTime(void)	{	return m_currentUpdateTime;	}
	
	const bool  & isBattleServer(void)	{	return m_battle_server;	}
protected:
	uint32		m_default_gid;
	String		m_default_group;
	bool		m_battle_server;
	bool		m_auto_town_check;

	//记录当前系统毫秒时间
        uint32          m_currentUpdateTime;

	CQueueThreadPool<uint32>     m_TownProcessPool;

       /// @copydoc ResourceManager::createImpl
        Resource* createImpl(const String& name, ResourceHandle handle,
            const String& group, bool isManual, ManualResourceLoader* loader,
            const NameValuePairList* createParams);
};


//自动处理Town自动信息，将需要处理的Town放入请求队列中.
class TownThread : public ThreadBase
{
        TownManager  * tm;
public:
        TownThread(TownManager * s) :ThreadBase("TownThread"),tm(s){}
        bool run()
        {
                Log.Success("TownThread","Towns Process thread start.");
                return tm->StartTownProcess();
        }
};


#define   sTownMgr   TownManager::getSingleton()



#endif
